<?php

namespace App\Models\Divination;

use App\Models\BasicModel;
use App\Models\User;
use App\Models\Users\MoneyLog;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\SoftDeletes;

class Answer extends BasicModel
{
    use HasDateTimeFormatter;

    protected $table = 'divination_answer';



    public function run($uid,$div_id){
        $order=Divination::where(['id'=>$div_id])->whereIn('status',[1,3])->first();
        if($uid == $order->uid) throw new \Exception('不能回答自己的问题');
        if(empty($order)) throw new \Exception('问题不存在');
        $user=User::query()->find($uid);
        if($user->zhanbu != 1) throw new \Exception('您不是认证占卜师 不能回答此问题');
        $answer=self::where(['div_id'=>$div_id,'teacher_id'=>$uid])->first();
        if(!empty($answer)) throw new \Exception('您已回答过该问题 不能重复回答');
        $money=bcmul(1,User::getRate($user->order_num),2);
        $balance = $order->balance - $money;
        if($balance>0){
            $order->balance = $balance;
        }else{
            $money = $order->balance;
            $order->balance = 0;
            $order->status = 4;
        }
        $order->answer_num++;
        $order->save();
        (new MoneyLog())->add($uid,$money,'占卜回答收入',5);
        return $money;

    }

    public function user()
    {
        return $this->belongsTo(User::class, 'teacher_id', 'id');
    }

    public function div()
    {
        return $this->belongsTo(Divination::class, 'div_id', 'id');
    }

}
